package com.damai.xml;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import com.citywithincity.utils.IoUtil;

public class XmlParser {

	
	public static Map parse(String content) throws IOException{
		StringReader reader = null;
		Map m = new HashMap();
		try{
			reader = new StringReader(content);
			SAXBuilder builder = new SAXBuilder();
			
			Document doc = builder.build(reader);
			Element root = doc.getRootElement();
			List list = root.getChildren();
			Iterator it = list.iterator();
			while(it.hasNext()) {
				Element e = (Element) it.next();
				String k = e.getName();
				Object v;
				List children = e.getChildren();
				if(children.isEmpty()) {
					v = e.getTextNormalize();
				} else {
					v = getChildMap(children);
				}
				m.put(k, v);
			}
			return m;
		} catch (JDOMException e) {
			throw new IOException(e);
		}finally{
			IoUtil.close(reader);
		}
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Map parse(InputStream in) throws IOException{
		Map m = new HashMap();
		try{
			SAXBuilder builder = new SAXBuilder();
			
			Document doc = builder.build(in);
			Element root = doc.getRootElement();
			List list = root.getChildren();
			Iterator it = list.iterator();
			while(it.hasNext()) {
				Element e = (Element) it.next();
				String k = e.getName();
				Object v;
				List children = e.getChildren();
				if(children.isEmpty()) {
					v = e.getTextNormalize();
				} else {
					v = getChildMap(children);
				}
				m.put(k, v);
			}
			return m;
		} catch (JDOMException e) {
			throw new IOException(e);
		}finally{
			IoUtil.close(in);
		}
	}
	

	@SuppressWarnings("rawtypes")
	private static Map<String, Object>  getChildMap(List children){
		Map<String, Object> data = new HashMap<String, Object>();
		Iterator it = children.iterator();
		while(it.hasNext()) {
			Element e = (Element) it.next();
			String name = e.getName();
			//List c = e.getChildren();
			Object value = e.getTextNormalize();
			data.put(name, value);
		}
		return data;
	}
}
